<?php
	
	include_once( "class/mustache/Mustache.php" );
	include_once( "class/mustache/MustacheLoader.php" );
	include_once( "class/wallMaintainance.php" );
	include_once( "class/wallDB.php" );
	
	class Wall2
	{
		private $tpl = "home";
		private $tplBase = "Plugins/Wall2/templates/";
		private $tplData;
		
		private $uid = 0;
		
		function __construct($uid)
		{
			$this->uid = $uid;
			$this->tplData = new stdClass();
		}
		
		function handle($P)
		{
			$op = isset($P["act"])?$P["act"]:"home";
			switch($op)
			{
			//async
				case "saveSettings":
					echo json_encode($this->saveSettings());
					exit;
					break;
				case "deleteAllDumps":
					echo json_encode($this->deleteAllDumps());
					exit;
					break;
				case "updateDBNow":
					echo json_encode($this->updateDBNow());
					exit;
					break;
				case "updateRequest":
					echo json_encode($this->updateRequest());
					exit;
					break;
				case "removeRequest":
					echo json_encode($this->removeRequest());
					exit;
					break;
				case "saveRequests":
					echo json_encode($this->saveRequests());
					exit;
					break;
			//views
				case "settings":
					$this->showSettings();
					break;
				case "makereq":
					$this->makeRequests();
					break;
				
				case "showreq":
					$this->showRequests();
					break;
					
				case "about":
					$this->showAbout();
					break;
					
				default:
					$this->showHome();
					break;
			}
			
			
			$this->render();
			
		}
		
		function deleteAllDumps()
		{
			return wallMaintainance::clearFiles(true);	
		}
		
		function updateDBNow()
		{
			$db = wallDB::getInstance();
			
			$res = wallMaintainance::parseXML(true);
			
			return $res;
		}
		
		function saveSettings()
		{
			global $postdata;
			
			$arSett = array();
			$arSett["postToFile"] = intval($postdata->postToFile);
			$arSett["postToCVEx"] = intval($postdata->postToCVEx);
			$arSett["postToCVLinkEx"] = intval($postdata->postToCVLinkEx);
			$arSett["showImages"] = intval($postdata->showImages);
			
			$db = wallDB::getInstance();
			foreach($arSett as $k=>$v)
				$db->setSetting($k, $v);
			
			return array("resp"=>true);
		}
		
		function updateRequest()
		{
			global $postdata;
			
			$idToUpdate = (isset($postdata->id))?$postdata->id:"";
			
			if ($idToUpdate=="")
				return array("resp"=>false);
				
			$postToFile = intval( $postdata->postToFile );
			$postToCVEx = intval( $postdata->postToCVEx );
			$postToCVLinkEx = intval( $postdata->postToCVLinkEx );
			$maxWanted = intval($postdata->maxWanted);
			
			$db = wallDB::getInstance();
			$db->query("UPDATE myrequests SET postToFile=$postToFile, postToCVEx=$postToCVEx, postToCVLinkEx=$postToCVLinkEx, maxWanted=$maxWanted WHERE id='$idToUpdate'");
			
			return array("resp"=>true);	
		}
		
		function removeRequest()
		{
			global $postdata;
			
			$idToRemove = (isset($postdata->id))?$postdata->id:"";
			
			if ($idToRemove=="")
				return array("resp"=>false);

			$db = wallDB::getInstance();
			$db->query("DELETE FROM myrequests WHERE id='$idToRemove'");
			
			return array("resp"=>true);			
		}
		
		function saveRequests()
		{
			global $postdata;
			
			$arReqs = isset($postdata->arReqs)?$postdata->arReqs:array();
			
			$db = wallDB::getInstance();
			
			//get my requests from DB
			$resMyReqs = $db->query("SELECT id FROM myrequests");
			$arMyReqs = array();
			while($dt = $resMyReqs->fetchArray(SQLITE3_ASSOC))
			{
				array_push($arMyReqs, $dt["id"]);
			}
				
			//what to del?
			$arDel = array_diff($arMyReqs, $arReqs);
			$arNew = array_diff($arReqs, $arMyReqs);
			
			//my settings
			$postToFile = intval( $db->getSetting('postToFile') );
			$postToCVEx = intval( $db->getSetting('postToCVEx') );
			$postToCVLinkEx = intval( $db->getSetting('postToCVLinkEx') );
			
			//what to add?
			foreach($arNew as $newR)
				$db->query("INSERT INTO myrequests 
								(id, postToFile, postToCVEx, postToCVLinkEx) 
							VALUES 
								('$newR', $postToFile, $postToCVEx, $postToCVLinkEx)");
			
			//what to del
			foreach($arDel as $delR)
				$db->query("DELETE FROM myrequests WHERE id='$delR'");
				
			$arResp = array();
			$arResp["resp"] = true;
			$arResp["added"] = count($arNew);
			$arResp["deleted"] = count($arDel);
			
			return $arResp;
		}
		
//--- Views ---		
		function showHome()
		{

			$this->tplData->viewTpl = "home";
			
			$ld = new LocalData();
			
			//get data
			$db = wallDB::getInstance();
			$this->tplData->curRevision = $db->getParsedVersion();
			$this->tplData->lastDateChecked = $ld->nicetime( $db->getSetting('lastDateChecked') );
			
			$this->tplData->activeRequests = $db->getActiveRequestsCount();
			$this->tplData->viralsCount = $db->getViralsCount();
			$this->tplData->totalRequestsCount = $db->getSetting('totalLinksCreated');
			
		}
		
		function showSettings()
		{
			$this->tplData->viewTpl = "settings";
			
			$db = wallDB::getInstance();
			
			$this->tplData->postToFile 		= (intval($db->getSetting('postToFile'))==1)?"checked":"";
			$this->tplData->postToCVEx 		= (intval($db->getSetting('postToCVEx'))==1)?"checked":"";
			$this->tplData->postToCVLinkEx 	= (intval($db->getSetting('postToCVLinkEx'))==1)?"checked":"";
			$this->tplData->showImages 	= (intval($db->getSetting('showImages'))==1)?"checked":"";
			
		}
		
		function showAbout()
		{
			$this->tplData->viewTpl = "about";
		}
		
		function showRequests()
		{
			
			date_default_timezone_set('Europe/Athens');
			
			$this->tplData->viewTpl = "showRequests";
			
			$db = wallDB::getInstance();
			
			$arMyReqs = $db->getMyRequests(false);			
			
			$ld = new LocalData();
			
			foreach($arMyReqs as &$arR)
			{
				//fix times
				$arR["lastWas"] = date("d M H:m:i", $arR["lastWas"]);
				$nT = $arR["nextWill"];
				$arR["nextWill"] = date("d M H:m:i", $nT);
				$arR["nextTS"] = $ld->nicetime($nT);
				
				//fic name (for wrap)
				$arR["showId"] = str_replace("_"," ", $arR["id"]);
				
				//get imPath
				$resI = $db->query("SELECT imPath FROM virals WHERE id='".$arR["id"]."' LIMIT 1");
				$dt = $resI->fetchArray();
				$imPath = $dt[0];
				
				$arR["imPath"] = ($imPath=="")?
									"templates/images/noImage.gif":
									"../../".$imPath;
				
				//fix chkcs
				$arR["postToFile"] = ($arR["postToFile"]==1)?"checked":"";
				$arR["postToCVEx"] = ($arR["postToCVEx"]==1)?"checked":"";
				$arR["postToCVLinkEx"] = ($arR["postToCVLinkEx"]==1)?"checked":"";
			}
			
			$this->tplData->arMyReqs = $arMyReqs;			
		}
		
		function makeRequests()
		{
			$this->tplData->viewTpl = "makeRequests";
			
			//get my requests
			$db = wallDB::getInstance();
			$arMyReqs = $db->getMyRequests(true);
			
			//get the latest revision
			$res = $db->query("SELECT MAX(revision) AS revision FROM virals LIMIT 1")->fetchArray();
			$curRev = $res["revision"];
			
			$showImages = intval( $db->getSetting('showImages') );
			$this->tplData->showImages = ($showImages==1);
			
			$res = $db->query("SELECT * FROM virals");
			$arVirals = array();
			$ite = 1;
			while($dt = $res->fetchArray())
			{
				$dt["displayReward"] = str_replace('reward_','', $dt["hostRewardsType"]);
				$dt["displayReward"] = str_replace('request_','', $dt["displayReward"]);
				$dt["displayReward"] = str_replace('hunterPrey_animalrescue_','', $dt["displayReward"]);
				$dt["displayReward"] = str_replace('hunterPrey_copsnbandits_','', $dt["displayReward"]);
				
				//imPath
				$dt["imPath"] = ($dt["imPath"]!="")?
								"../../".$dt["imPath"]:
								"templates/images/noImage.gif";
				
				$dt["isChecked"] = in_array($dt["id"], $arMyReqs);
				$dt["classNewest"] = ($curRev==$dt["revision"])?"classNewest":"";
				$dt["ite"] = $ite;
				array_push($arVirals, $dt);
				++$ite;
			}
			
			$this->tplData->arVirals = $arVirals;
		}
		
//--- Helpers ----
		private function render()
		{
			$m = new Mustache();
			$ml = new MustacheLoader($this->tplBase,"tpl");
			
			$viewHtml = file_get_contents($this->tplBase.$this->tplData->viewTpl.".tpl");
			
			echo $m->render( 
						$viewHtml ,
						$this->tplData, $ml
					);
		}
		
		
		
	}
	
?>